package com.ljc.cjgl.service;

import java.util.Date;
import java.util.List;
import java.util.Optional;

import javax.transaction.Transactional;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.ljc.cjgl.entitiy.Course;
import com.ljc.cjgl.entitiy.Knowledge;
import com.ljc.cjgl.form.KnowledgeForm;
import com.ljc.cjgl.repository.KnowledgeRepository;

@Service
public class KnowledgeService {
	@Autowired
	private KnowledgeRepository knowledgeDAO;
	
	
	public Knowledge findById(Integer id) {
		Optional<Knowledge> optional = knowledgeDAO.findById(id);
		if(optional.isPresent()) {
			return optional.get();
		}
		return null;
	}
	
	public List<Knowledge> findAll(){
		return knowledgeDAO.findAll();
	}
	
	public List<Knowledge> findAll(Specification<Knowledge> specification){
		return knowledgeDAO.findAll(specification);
	}
	
	public Page<Knowledge> findAll(Specification<Knowledge> specification ,Pageable pageable){
		return knowledgeDAO.findAll(specification, pageable);
	}

	@Transactional
	public synchronized boolean save(KnowledgeForm form,String userName) {
		Knowledge model=new Knowledge();
		
		try {
			if(form.getId()!=null) {
				model=findById(form.getId());
			}
			if(form.getCourseId()!=null) {
				model.setCourse(new Course(form.getCourseId()));
			}
			if(model.getCreateDate()==null) {
				model.setCreateDate(new Date());
			}
			if(model.getCreator()==null) {
				model.setCreator(userName);
			}
			BeanUtils.copyProperties(form, model);
			knowledgeDAO.save(model);
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	
	public synchronized boolean delete(List<Knowledge> knowledges) {
		try {
			for (Knowledge know : knowledges) {
				knowledgeDAO.deleteById(know.getId());
			}
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	
	
}
